<template>
  <DialogCom :draggable="true" :title="title" :width="'500'" :visible="isVisible" @close="close" @confirm="confirm">
    <template v-slot:content>
      <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="90px" class="demo-ruleForm" status-icon>
        <el-form-item label="文件:" prop="shp">
          <div class="path">
            <el-input v-model="formData.shp" placeholder="请上传SHP文件压缩包" disabled />
            <input v-show="false" ref="upfileRef" type="file" title=" " @change="upLoadFile" multiple="multiple"
              style="display: none" />
            <el-button class="common-btn" @click="selectFile">上传</el-button>
          </div>
        </el-form-item>
        <el-form-item label="名称字段:" prop="prop" v-if="type != 'ClipFlat'">
          <el-select v-model="formData.prop" placeholder="请先上传SHP文件再选择字段">
            <el-option v-for="(item, index) in selArr" :key="index" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="高程:" prop="height" v-if="type == 'HeightMask'">
          <el-input v-model="formData.height" type="number" :step="1" :min="0" @change="editHandle" />
        </el-form-item>
        <el-form-item label="柱体高度:" prop="cylinderHeight" v-if="type == 'ClipFlat'">
          <el-input v-model="formData.cylinderHeight" type="number" :step="1" :min="0" @change="editCylinderHeight" />

        </el-form-item>
        <el-form-item label="编辑模式:" prop="operation" v-if="type == 'ClipFlat'">
          <el-select v-model="formData.operation" placeholder="请选择编辑模式">
            <el-option v-for="item in operationMode" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
    </template>
  </DialogCom>
  <FileServer v-if="currentDialog == 'file'" @close="currentDialog = undefined" @confirm="fileConfirm"
    :fileAccept="'zip数据(*.zip)|*.zip'" />
</template>

<script setup>
import { ref, defineProps } from 'vue'
import DialogCom from '@/components/common/DialogCom.vue'
import { upShpZip, upShp, reqGetShpFeatures } from '@/api/modelser2Api'
import { ElMessage } from 'element-plus'
import loading from "@/api/loading"
import FileServer from '@/components/FileServer.vue'
import { getOs, reqDownloadFile } from "@/api/modelser2Api";
import { isLocalhost } from "@/scripts/utils";

// 上传文件
const upfileRef = ref(null)
let arr = []
let fromDataArr = []
const selArr = ref([])
const typeList = ref([{ label: '散列', value: 'file' }])
const ruleFormRef = ref('')
const currentDialog = ref(undefined)

const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false,
  },
  close: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '',
  },
  type: {
    type: String,
    default: '',
  },
})
const emits = defineEmits(['close', 'confirm'])
const formData = ref({
  shp: '',
  prop: '',
  serverPath: '',
  features: '',
  height: 0,
  operation: "1",
  cylinderHeight: 10
})

const rules = ref({
  prop: [{ required: true, message: '请选择字段', trigger: 'blur' }],
  shp: [{ required: true, message: '请上传SHP文件压缩包', trigger: 'blur' }],
  height: [{ required: true, message: '请输入高程', trigger: 'blur' }],
  cylinderHeight: [{ required: true, message: '请输入柱体高度', trigger: 'blur' }],
  operation: [{ required: true, message: '请选择编辑模式', trigger: 'blur' }],
})

// 裁剪方式
const operationMode = [
  {
    value: "1",
    label: "裁剪",
  },
  {
    value: "2",
    label: "压平",
  },
  // {
  //   value: "3",
  //   label: "单体化",
  // },
];


const selectFile = async () => {
  const res = await getOs()
  if ((await getOs()) == 'win' && isLocalhost) {
    upfileRef.value.click()
  } else {
    currentDialog.value = 'file'
  }
}

const editHandle = (value) => {
  // 将输入值强制转换为数字，并确保不小于 0.1
  const numValue = Number(value);
  if (numValue <= 0 || isNaN(numValue)) {
    formData.value.height = 0
  }
}

const editCylinderHeight = (value) => {
  // 将输入值强制转换为数字，并确保不小于 0.1
  const numValue = Number(value);
  if (numValue <= 0 || isNaN(numValue)) {
    formData.value.cylinderHeight = 0
  }
}

const upLoadFile = async (e) => {
  console.log(e.target.files);

  const files = e.target.files
  if (files.length === 0) return
  Object.keys(files).forEach((key) => {
    arr.push(files[key].name)
  })
  formData.value.shp = arr.join(',')
  arr = []
  let filesData = new FormData()
  for (let i = 0; i <= files.length - 1; i++) {
    filesData.append('file', files[i])
  }

  if (files.length > 1) {
    try {
      const res = await upShp(filesData)

      if (res.code === 1000) {
        ElMessage.success('上传成功')
        if (res.code === 1000) {
          // let getFeatureData = new FormData()
          // getFeatureData.append('path', res.data)
          formData.value.serverPath = res.data
          setTimeout(async () => {
            const data = {
              "path": res.data
            }
            await getShpFeatures(data)
          }, 200)
        }
      }
    } catch (error) {
      console.log(error)
    }
  } else {
    try {
      const res = await upShpZip(filesData)

      if (res.code == 1000) {
        ElMessage.success('上传成功')
        if (res.code === 1000) {
          // let getFeatureData = new FormData()
          // getFeatureData.append('path', res.data)
          formData.value.serverPath = res.data

          setTimeout(async () => {
            const data = {
              "path": res.data
            }
            await getShpFeatures(data)
          }, 200)
        }
      }
    } catch (error) {
      console.log(error)
    }
  }
}

// 将二进制字符串转换为精确匹配图片的 File 对象
const createExactFileFromBinary = (binaryData, fileName) => {

  // 创建 Blob
  const blob = new Blob([binaryData], {
    type: 'application/x-zip-compressed'
  });

  // 创建精确匹配图片属性的 File 对象
  const file = new File([blob], fileName, {
    type: 'application/x-zip-compressed',
    lastModified: 1762746460247  // 图片中的时间戳
  });

  // 添加其他只读属性（通过 Object.defineProperty）
  Object.defineProperty(file, 'lastModifiedDate', {
    value: new Date("Mon Nov 10 2025 11:47:40 GMT+0800"),
    writable: false,
    enumerable: true
  });

  Object.defineProperty(file, 'webkitRelativePath', {
    value: "",
    writable: false,
    enumerable: true
  });

  Object.defineProperty(file, 'size', {
    value: 1015025,  // 图片中的文件大小
    writable: false,
    enumerable: true
  });

  return file;
};

// 创建匹配图片的 FileList 对象
const createExactFileList = (file) => {
  const fileList = {
    0: file,
    length: 1,
    item: function (index) {
      return index === 0 ? file : null;
    }
  };

  // 添加原型信息
  Object.defineProperty(fileList, '[[Prototype]]', {
    value: 'FileList',
    enumerable: false
  });

  return fileList;
};

// 下载shp压缩包并上传
const verificationShp = async (arrayBuffer, fileName) => {
  try {
    // 创建精确匹配图片的 File 对象
    const file = createExactFileFromBinary(arrayBuffer, fileName);

    // 创建 FileList
    const fileList = createExactFileList(file);
    const files = fileList;

    if (files.length === 0) return;

    // 保持原有逻辑
    let arr = [];
    Object.keys(files).forEach((key) => {
      if (!isNaN(key)) {
        arr.push(files[key].name);
      }
    });
    formData.value.shp = arr.join(',');
    arr = [];

    let filesData = new FormData();
    for (let i = 0; i < files.length; i++) {
      filesData.append('file', files[i]);
    }

    // 上传 ZIP 文件
    const res = await upShpZip(filesData);

    if (res.code === 1000) {
      ElMessage.success('上传成功');
      formData.value.serverPath = res.data;

      setTimeout(async () => {
        const data = { "path": res.data };
        await getShpFeatures(data);
      }, 200);
    }
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error('上传失败: ' + error.message);
  }
};


const getShpFeatures = async (data) => {
  selArr.value = []
  formData.value.prop = ""
  try {
    const ret = await reqGetShpFeatures(data)
    console.log(ret.data);
    if (ret.code !== 1000) {
      loading.closeLoading()
      ElMessage({
        message: "获取失败",
        type: 'error',
      })
      return;
    }
    loading.closeLoading()

    formData.value.features = ret.data;
    const prop = ret.data[0].prop
    Object.keys(prop).forEach((key) => {
      selArr.value.push(key)
    })
    ElMessage({
      message: `shp文件验证通过，包含${formData.value.features.length}个多边形`,
      type: 'success',
    })
  } catch (error) {
    loading.closeLoading()
    console.log(error)
  }
}

/**
 * 选择的文件路径
 * @param path
 */
const fileConfirm = async (path) => {
  try {
    const arr = path.split('\\')
    const res = await reqDownloadFile(encodeURIComponent(path))
    await verificationShp(res, arr[arr.length - 1])
    loading.closeLoading()
  } catch (error) {
    loading.closeLoading()
    console.log(error)
  }
  currentDialog.value = undefined
}

const close = () => {
  emits('close')
}
// 确认
const confirm = () => {
  ruleFormRef.value.validate((valid) => {
    if (!valid) return
    emits('confirm', {
      path: formData.value.serverPath,
      nameField: formData.value.prop,
      features: formData.value.features,
      height: Number(formData.value.height),
      operation: formData.value.operation,
      cylinderHeight: Number(formData.value.cylinderHeight),
    })
  })
}
</script>

<style scoped>
.el-form-item .el-textarea,
.el-form-item .el-select,
.el-form-item .el-input {
  width: 300px !important;
}

.item {
  width: 300px;
}

.path {
  display: grid;
  grid-template-columns: 300px 70px;
  grid-column-gap: 5px;
}
</style>
